package _0014;

/**
 * Created by HMF on 2021/05/14 07:28
 */

import java.util.Arrays;

/**
 * 0014.最长公共前缀
 */
public class Solution {

    public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 1) { // 只有一个元素时，直接返回
            return strs[0];
        }

        // 两个或两个以上元素时
        int length = 0;

        int strLength = strs[0].length(); // 获取字符串数组里的字符串最小长度，使用第一个元素初始化
        for (int i = 1; i < strs.length; i++) { // 遍历字符串数组，获取最小长度
            if (strs[i].length() < strLength) {
                strLength = strs[i].length();
            }
        }

        for (int i = 0; i < strLength; i++) { //
            boolean flag = false;

            for (int j = 0; j < strs.length - 1; j++) {
                if (strs[j].charAt(i) == strs[j + 1].charAt(i)) {
                    continue;
                } else {
                    flag = true;
                    break;
                }
            }

            if (flag) {
                break;
            } else {
                length++;
            }

        }
        if (length == 0) {
            return "";
        } else {
            return strs[0].substring(0, length);
        }
    }

    public static String longestCommonPrefixOther(String[] strs) {
        if (strs.length == 1) { // 只有一个元素时，直接返回
            return strs[0];
        }

        // 两个或两个以上元素时
        StringBuffer sb = new StringBuffer("");

        int strLength = strs[0].length(); // 获取字符串数组里的字符串最小长度，使用第一个元素初始化
        for (int i = 1; i < strs.length; i++) { // 遍历字符串数组，获取最小长度
            if (strs[i].length() < strLength) {
                strLength = strs[i].length();
            }
        }

        for (int i = 0; i < strLength; i++) { //
            boolean flag = false;

            for (int j = 0; j < strs.length - 1; j++) {
                if (strs[j].charAt(i) == strs[j + 1].charAt(i)) {
                    continue;
                } else {
                    flag = true;
                    break;
                }
            }

            if (flag) {
                break;
            } else {
                sb.append(strs[0].charAt(i));
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
//        String[] strs = {"flower", "flow", "flight"};
        String[] strs = {"dog", "racecar", "car"};
//        String[] strs = {"a"};
//        String[] strs = {"acb", "acc"};
//        String[] strs = {"ac", "a"};

        String prefix = longestCommonPrefix(strs);

        System.out.println(Arrays.toString(strs));
        System.out.println("最长前缀是：" + prefix);
    }
}
